<template>
    <div class="my-auctions">
        <div class="page-header">
            <h2>我的拍卖品</h2>
            <div class="right-actions">
                <el-button type="primary" @click="navigateToPublish">
                    <el-icon>
                        <Plus />
                    </el-icon>发布新拍卖品
                </el-button>
            </div>
        </div>

        <!-- 搜索和筛选 -->
        <el-card shadow="hover" class="filter-card">
            <el-form :inline="true" :model="queryParams" class="filter-form">
                <el-form-item label="拍品名称">
                    <el-input v-model="queryParams.title" placeholder="请输入拍品名称" clearable />
                </el-form-item>

                <el-form-item label="拍卖状态">
                    <el-select v-model="queryParams.status" placeholder="全部状态" clearable>
                        <el-option label="待审核" value="PENDING_REVIEW" />
                        <el-option label="审核拒绝" value="REVIEW_REJECTED" />
                        <el-option label="即将开始" value="PENDING" />
                        <el-option label="正在进行" value="ACTIVE" />
                        <el-option label="已结束" value="FINISHED" />
                        <el-option label="已取消" value="CANCELLED" />
                    </el-select>
                </el-form-item>

                <el-form-item label="发布时间">
                    <el-date-picker v-model="queryParams.timeRange" type="daterange" range-separator="至"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleQuery">
                        <el-icon>
                            <Search />
                        </el-icon>查询
                    </el-button>
                    <el-button @click="resetQuery">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 拍卖品表格 -->
        <el-card shadow="hover" class="table-card">
            <div class="table-container" v-loading="loading">
                <el-table :data="auctionList" stripe style="width: 100%" @row-click="viewAuctionDetail" row-key="id">
                    <el-table-column label="拍品图片" width="120" align="center">
                        <template #default="scope">
                            <el-image :src="scope.row.image || 'https://via.placeholder.com/80x80'"
                                :preview-src-list="[scope.row.image]" fit="cover"
                                style="width: 80px; height: 80px; border-radius: 4px" />
                        </template>
                    </el-table-column>

                    <el-table-column prop="title" label="拍品名称" min-width="180" show-overflow-tooltip>
                        <template #default="scope">
                            <div style="cursor: pointer; color: #409EFF; font-weight: bold">
                                {{ scope.row.title }}
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="startPrice" label="起拍价" width="100" align="center">
                        <template #default="scope">
                            <span class="price">¥{{ scope.row.startPrice }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="currentPrice" label="当前价" width="100" align="center">
                        <template #default="scope">
                            <span class="price highlight">
                                ¥{{ scope.row.currentPrice || scope.row.startPrice }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="status" label="状态" width="100" align="center">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)" effect="light">
                                {{ getStatusText(scope.row.status) }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column label="拍卖时间" min-width="200">
                        <template #default="scope">
                            <div v-if="['PENDING', 'ACTIVE', 'FINISHED'].includes(scope.row.status)">
                                <div>开始: {{ formatDate(scope.row.startTime) }}</div>
                                <div>结束: {{ formatDate(scope.row.endTime) }}</div>
                            </div>
                            <div v-else>
                                <div>创建: {{ formatDate(scope.row.createTime) }}</div>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作" width="280" fixed="right">
                        <template #default="scope">
                            <div style="display: flex; gap: 8px;">
                                <el-button size="small" @click.stop="viewAuctionDetail(scope.row)" plain>
                                    查看
                                </el-button>

                                <!-- 允许编辑所有状态的拍卖 -->
                                <el-button size="small" type="primary" @click.stop="editAuction(scope.row)" plain>
                                    {{ ['PENDING', 'ACTIVE'].includes(scope.row.status) ? '编辑' : '详情' }}
                                </el-button>

                                <!-- 允许取消PENDING和ACTIVE状态的拍卖 -->
                                <el-button v-if="['PENDING', 'ACTIVE'].includes(scope.row.status)" size="small" type="danger"
                                    @click.stop="handleCancelAuction(scope.row)" plain>
                                    取消
                                </el-button>
                                <!-- 允许删除FINISHED和REVIEW_REJECTED状态的拍卖 -->
                                <el-button v-if="['FINISHED', 'REVIEW_REJECTED'].includes(scope.row.status)" size="small" type="danger"
                                    @click.stop="handleDeleteAuction(scope.row)" plain>
                                    删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 空数据提示 -->
                <el-empty v-if="auctionList.length === 0 && !loading" description="暂无拍卖品">
                    <el-button type="primary" @click="navigateToPublish">发布拍卖品</el-button>
                </el-empty>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-if="total > 0" v-model:current-page="queryParams.page"
                    v-model:page-size="queryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <!-- 编辑拍卖品对话框 -->
        <el-dialog v-model="editDialogVisible" :title="'编辑拍卖品 - ' + editForm.title" width="50%" destroy-on-close>
            <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="100px" label-position="left" status-icon>
                <el-form-item label="拍品名称" prop="title">
                    <el-input v-model="editForm.title" placeholder="请输入拍品名称" />
                </el-form-item>

                <el-form-item label="拍品分类" prop="categoryId">
                    <el-select v-model="editForm.categoryId" placeholder="选择分类">
                        <el-option v-for="category in categoryList" :key="category.id" :label="category.name" :value="category.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="拍品描述" prop="description">
                    <el-input v-model="editForm.description" type="textarea" :rows="5" placeholder="请详细描述拍品的特点、来源、品相等信息" />
                </el-form-item>

                <el-form-item label="拍品图片" prop="image">
                    <el-upload class="upload-container" :http-request="handleUpload" :before-upload="beforeUpload"
                        :on-exceed="handleExceed" :limit="1" :file-list="editFileList" list-type="picture-card"
                        :on-remove="handleRemove">
                        <el-icon><Plus /></el-icon>
                        <template #tip>
                            <div class="upload-tip">请上传清晰的拍品照片，支持jpg、png格式，最大5MB</div>
                        </template>
                    </el-upload>
                </el-form-item>

                <el-form-item label="起拍价" prop="startPrice">
                    <el-input-number v-model="editForm.startPrice" :min="1" :precision="2" :step="10" class="price-input" />
                    <span class="unit">元</span>
                </el-form-item>

                <el-form-item label="拍卖时间" prop="auctionTime" class="with-tip">
                    <el-date-picker v-model="editForm.auctionTime" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                        format="YYYY-MM-DD HH:mm" range-separator="至" value-format="YYYY-MM-DD HH:mm:ss" @change="handleTimeChange"
                        :unlinkPanels="true" :clearable="false" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleUpdateAuction" :loading="submitting">保存修改</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getSellerAuctions, cancelAuction as cancelAuctionApi, getAuctionById, updateAuction, uploadImage, deleteAuction } from '@/api/seller'
import { getUserCategoryList } from '@/api/category'

const router = useRouter()
const loading = ref(false)
const auctionList = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
    title: '',
    status: '',
    timeRange: [],
    page: 1,
    pageSize: 10
})

// 获取拍卖品列表
const fetchAuctionList = async () => {
    loading.value = true

    try {
        // 构建查询参数
        const params = { ...queryParams }

        // 处理时间范围
        if (params.timeRange && params.timeRange.length === 2) {
            params.startDate = params.timeRange[0]
            params.endDate = params.timeRange[1]
        }
        delete params.timeRange

        console.log('请求卖家拍卖品列表参数:', params)
        const res = await getSellerAuctions(params)
        console.log('获取卖家拍卖品列表响应:', res)

        if (res && res.code === 1 && res.data) {
            const pageResult = res.data
            console.log('解析到的分页数据:', pageResult)
            auctionList.value = pageResult.records || []
            total.value = pageResult.total || 0
        } else {
            auctionList.value = []
            total.value = 0
            ElMessage.warning('获取拍卖品列表失败')
        }
    } catch (error) {
        console.error('获取拍卖品列表失败:', error)
        ElMessage.error('获取拍卖品列表失败，请稍后再试')
        auctionList.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 查询按钮点击事件
const handleQuery = () => {
    queryParams.page = 1
    fetchAuctionList()
}

// 重置查询条件
const resetQuery = () => {
    Object.assign(queryParams, {
        title: '',
        status: '',
        timeRange: [],
        page: 1,
        pageSize: 10
    })
    fetchAuctionList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
    queryParams.pageSize = val
    fetchAuctionList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
    queryParams.page = val
    fetchAuctionList()
}

// 跳转到发布拍卖品页面
const navigateToPublish = () => {
    router.push('/user/seller/auction/publish')
}

// 查看拍卖详情
const viewAuctionDetail = (row) => {
    router.push(`/market/auction/${row.id}`)
}

// 编辑相关数据
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const categoryList = ref([])
const submitting = ref(false)
const editFileList = ref([])

// 上传前验证
const beforeUpload = (file) => {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt5M = file.size / 1024 / 1024 < 5

    if (!isImage) {
        ElMessage.error('只能上传jpg/png格式的图片！')
        return false
    }
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过5MB！')
        return false
    }
    return true
}

// 处理文件上传
const handleUpload = async ({ file }) => {
    try {
        const res = await uploadImage(file)
        if (res) {
            editForm.image = res
            editFileList.value = [{ url: res, name: file.name }]
            ElMessage.success('图片上传成功')
        } else {
            ElMessage.error('图片上传失败')
        }
    } catch (error) {
        console.error('上传图片失败:', error)
        ElMessage.error('图片上传失败，请重试')
    }
}

// 超出上传数量限制
const handleExceed = () => {
    ElMessage.warning('只能上传1张图片')
}

// 处理图片移除
const handleRemove = () => {
    editForm.image = ''
    editFileList.value = []
}

// 编辑表单数据
const editForm = reactive({
    id: '',
    title: '',
    description: '',
    categoryId: '',
    startPrice: 100,

    image: '',
    auctionTime: [],
    status: ''
})

// 监听拍卖时间变化
watch(() => editForm.auctionTime, (newVal) => {
    if (newVal && newVal.length === 2) {
        console.log('拍卖时间已更新:', newVal)
    }
}, { deep: true })

// 编辑表单验证规则
const editRules = {
    image: [{ required: true, message: '请上传拍品图片', trigger: 'change' }],
    title: [{ required: true, message: '请输入拍品名称', trigger: 'blur' }],
    categoryId: [{ required: true, message: '请选择拍品分类', trigger: 'change' }],
    description: [{ required: true, message: '请输入拍品描述', trigger: 'blur' }],
    startPrice: [{ required: true, message: '请设置起拍价', trigger: 'blur' }],

    auctionTime: [{ required: true, message: '请设置拍卖时间', trigger: 'change' }]
}

// 获取分类列表
const fetchCategories = async () => {
    try {
        const res = await getUserCategoryList()
        if (res && res.code === 1) {
            categoryList.value = res.data || []
        }
    } catch (error) {
        console.error('获取分类列表失败:', error)
    }
}

// 编辑拍卖
const editAuction = async (row) => {
    try {
        const res = await getAuctionById(row.id)
        if (res && res.code === 1 && res.data) {
            const auction = res.data
            // 填充表单数据
            Object.assign(editForm, {
                id: auction.id,
                title: auction.title,
                categoryId: auction.categoryId,
                image: auction.image,
                description: auction.description,
                startPrice: auction.startPrice,

                status: auction.status,
                auctionTime: [auction.startTime, auction.endTime]
            })
            // 初始化图片列表
            editFileList.value = auction.image ? [{ url: auction.image, name: '当前图片' }] : []
            editDialogVisible.value = true
        } else {
            ElMessage.error('获取拍卖品详情失败')
        }
    } catch (error) {
        console.error('获取拍卖品详情失败:', error)
        ElMessage.error('获取拍卖品详情失败，请稍后再试')
    }
}

// 处理时间变化
const handleTimeChange = (val) => {
    if (val && val.length === 2) {
        editForm.auctionTime = val
        console.log('拍卖时间更新为:', val)
    }
}

// 更新拍卖品
const handleUpdateAuction = () => {
    if (!editFormRef.value) return

    editFormRef.value.validate(async (valid) => {
        if (!valid) return

        submitting.value = true
        try {
            // 构建提交数据
            const submitData = {
                ...editForm,
                startTime: editForm.auctionTime[0],
                endTime: editForm.auctionTime[1]
            }
            delete submitData.auctionTime

            const res = await updateAuction(submitData)
            if (res.code === 1) {
                ElMessage.success('修改成功')
                editDialogVisible.value = false
                fetchAuctionList() // 刷新列表
            } else {
                ElMessage.error(res?.msg || '修改失败')
            }
        } catch (error) {
            console.error('修改拍卖品失败:', error)
            ElMessage.error('修改失败，请稍后再试')
        } finally {
            submitting.value = false
        }
    })
}

// 取消拍卖
const handleCancelAuction = (row) => {
    ElMessageBox.confirm(`确定要取消拍卖品"${row.title}"吗？此操作不可恢复。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await cancelAuctionApi(row.id)
            if (res.data && res.data.code === 1) {
                ElMessage.success('取消拍卖成功')
                fetchAuctionList() // 刷新列表
            } else {
                ElMessage.error(res.data?.msg || '取消拍卖失败')
            }
        } catch (error) {
            console.error('取消拍卖失败:', error)
            ElMessage.error('取消拍卖失败，请稍后再试')
        }
    }).catch(() => {
        // 用户取消操作，不做处理
    })
}

// 删除拍卖品
const handleDeleteAuction = (row) => {
    ElMessageBox.confirm(`确定要删除拍卖品"${row.title}"吗？此操作不可恢复。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteAuction(row.id)
            if (res.code === 1) {
                ElMessage.success('删除成功')
                fetchAuctionList() // 刷新列表
            } else {
                ElMessage.error(res?.msg || '删除失败')
            }
        } catch (error) {
            console.error('删除拍卖品失败:', error)
            ElMessage.error('删除失败，请稍后再试')
        }
    }).catch(() => {
        // 用户取消操作，不做处理
    })
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '-'
    // 确保日期字符串包含T和时区信息
    const isoStr = dateStr.replace(' ', 'T') + '+08:00'
    const date = new Date(isoStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
}

// 获取状态标签类型
const getStatusType = (status) => {
    const statusMap = {
        'PENDING_REVIEW': 'info',
        'REVIEW_REJECTED': 'danger',
        'PENDING': 'warning',
        'ACTIVE': 'success',
        'FINISHED': 'info',
        'CANCELLED': 'danger'
    }
    return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
    const statusMap = {
        'PENDING_REVIEW': '待审核',
        'REVIEW_REJECTED': '审核拒绝',
        'PENDING': '即将开始',
        'ACTIVE': '进行中',
        'FINISHED': '已结束',
        'CANCELLED': '已取消'
    }
    return statusMap[status] || '未知'
}

onMounted(() => {
    fetchAuctionList()
    fetchCategories()
})
</script>

<style scoped>
.my-auctions {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.filter-card {
    margin-bottom: 20px;
}

.filter-form {
    display: flex;
    flex-wrap: wrap;
}

.table-card {
    margin-bottom: 20px;
}

.table-container {
    min-height: 300px;
}

.price {
    font-weight: bold;
}

.price.highlight {
    color: #f56c6c;
}

.item-id {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.price-input {
    width: 200px;
}

.unit {
    margin-left: 10px;
    color: #606266;
}

.with-tip .form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
    line-height: 1.5;
}
</style>